package org.adream.account.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.adream.account.dao.RealNameAuthDao;
import org.adream.account.dao.RealNameTmpDao;
import org.adream.account.dao.RoleDao;
import org.adream.account.dao.UserDao;
import org.adream.account.dao.UserRoleLinkDao;
import org.adream.account.dao.UserVerifyDao;
import org.adream.account.dao.UserVerifyHistoryDao;
import org.adream.account.entity.CoachPlanRoleEntity;
import org.adream.account.entity.RealNameAuthEntity;
import org.adream.account.entity.RealNameTmpEntity;
import org.adream.account.entity.RoleEntity;
import org.adream.account.entity.UserEntity;
import org.adream.account.entity.UserRoleLinkEntity;
import org.adream.account.entity.UserVerifyEntity;
import org.adream.account.model.ResultModel;
import org.adream.account.model.SynDream2020DataModel;
import org.adream.account.rest.api.model.DataTableRequest;
import org.adream.account.service.async.SynDream2020Service;
import org.adream.account.service.library.SynLibraryService;
import org.adream.account.service.library.SynLibraryUserEntity;
import org.adream.account.util.Constant;
import org.adream.account.util.IdGenerator;
import org.adream.account.util.SensorDataUtil;
import org.adream.account.util.Utils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sensorsdata.analytics.javasdk.SensorsAnalytics;
import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException;

@Service
public class UserVerifyService {
	
	private final static Logger logger = LoggerFactory.getLogger(UserVerifyService.class);
	
	@Autowired
	private UserVerifyDao verifyDao;
	
	@Autowired
	private UserVerifyHistoryDao verifyHistoryDao;

	@Autowired
	private RealNameAuthDao authDao;
	
	@Autowired
	private RealNameTmpDao tmpDao;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private HttpSession session;
	
	@Autowired
	private SynDream2020Service synDream2020Service;
	
	@Autowired
	private SynLibraryService synLibraryService;
	
	@Autowired
	private UserRoleLinkDao userRoleDao;
	
	@Autowired
	private OcrService ocrService;
	
	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private SensorDataUtil sensorDataUtil;
	
	/**
	 * 新增
	 * @param verify
	 */
	public ResultModel<String> addUserVerify(UserVerifyEntity verify) {
		verify.setState(Constant.ONE);
		verify.setCheckResult("正在审核中,请您耐心等候.");
		String uid = (String)session.getAttribute("uid");
		verify.setCreator(uid);
		verify.setCts(new Date());
		verify.setModifier(uid);
		verify.setMts(new Date());
		verify.setDr(Constant.ONE); 
		int result = verifyDao.addUserVerify(verify);
		if(result == 0) {
			return new ResultModel<String>(ResultModel.ERR_DATABASE, "系统错误,请联系系统管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 删除   逻辑删除
	 * @param uid user id
	 * @param rleId role id
	 * 删除"认证方式"不影响"实名认证"
	 */
	public ResultModel<String> deleteUserVerify(String uid, String rleId) {
		UserVerifyEntity verify = verifyDao.queryVerifyByUidAndRleIdAndDr(uid, rleId, Constant.ONE);
		if(verify == null) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "删除失败,认证不存在", null);
		}
		
		String modifier = (String)session.getAttribute("uid");
		verify.setModifier(modifier);
		verify.setMts(new Date());
		verify.setDr(Constant.ZERO);
		int result = verifyDao.deleteUserVerify(verify);
		if(result == 0) {
			return new ResultModel<String>(ResultModel.ERR_DATABASE, "系统错误,请联系系统管理员", null);
		}
		userRoleDao.deleteUserRole(uid, rleId);
		/**
		 * 若删除的是'梦想教师'认证,影响isTeacher,isDreamDirector数据
		 * 若删除的是'志愿者'认证,暂不同步
		 * 身份认证不影响'实名'角色信息
		 */
		if(verify.getSort() == Constant.TEACHER_SORT) {
			SynDream2020DataModel data = new SynDream2020DataModel();
			data.setCasid(uid);
			data.setSchoolNumber(verify.getSchool().getSid());
			data.setIsTeacher(false);
			data.setIsDreamDirector(false);
			synDream2020Service.synDream2020Data(data);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 *   审核"身份认证"并且同步数据  后台
	 * @param processType  处理类型  自动处理：auto  此时不需要更新实名信息， null时 为后台处理 
	 * @param uid
	 * @param rleId
	 * @param verifyEntity
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = ADreamServiceException.class, isolation = Isolation.DEFAULT)
	public ResultModel<?> checkVerifyAndSynData(String processType,String uid,String rleId,UserVerifyEntity verifyEntity) {
		logger.debug("身份管理审核身份认证");
		//神策数据'盒子_用户身份审核结果'事件埋点
		SensorsAnalytics sa = null;
		try {
			sa = sensorDataUtil.getSensorsAnalytics();
		} catch (IOException e) {
			logger.warn("审核失败," + e.getMessage());
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0112-1,请联系管理员", null);
		}
		Map<String, Object> properties = new HashMap<>();
		properties.put("review_status", "拒绝");
		if(StringUtils.isEmpty(uid) || StringUtils.isEmpty(rleId) || verifyEntity == null || verifyEntity.getState() == null) {
			logger.warn("审核身份认证失败,参数有误:(");
			properties.put("failure_reason", "参数有误");
			try {
				sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_RESULT, properties);
				sa.flush();
			} catch (InvalidArgumentException e) {
				logger.warn("审核失败," + e.getMessage());
				return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0112-2,请联系管理员", null);
			}
			return new ResultModel<String>(ResultModel.ERR_PARAM, ResultModel.ERR_PARAM_MSG, null);
		}
		if(!StringUtils.isEmpty(verifyEntity.getCheckResult()) && verifyEntity.getCheckResult().length() > Constant.LONG_DATA_LENGTH) {
			logger.warn("审核身份认证失败,审核说明太长,请精简:(");
			properties.put("failure_reason", "审核说明太长");
			try {
				sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_RESULT, properties);
				sa.flush();
			} catch (InvalidArgumentException e) {
				logger.warn("审核失败," + e.getMessage());
				return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0112-3,请联系管理员", null);
			}
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "审核说明输入太长,请精简", null);
		}
		UserVerifyEntity verify = verifyDao.queryVerifyByUidAndRleIdAndDr(uid, rleId,Constant.ONE);
		if(verify == null) {
			logger.warn("审核失败,未查询到相应数据:(");
			properties.put("failure_reason", "数据不存在");
			try {
				sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_RESULT, properties);
				sa.flush();
			} catch (InvalidArgumentException e) {
				logger.warn("审核失败," + e.getMessage());
				return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0112-4,请联系管理员", null);
			}
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "审核失败,无相关数据", null);
		}
		if(verify.getSort() == null) {
			logger.warn("审核失败,sort为空:(");
			properties.put("failure_reason", "参数sort为空");
			try {
				sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_RESULT, properties);
				sa.flush();
			} catch (InvalidArgumentException e) {
				logger.warn("审核失败," + e.getMessage());
				return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0112-5,请联系管理员", null);
			}
			return new ResultModel<String>(ResultModel.ERR_PARAM, "审核失败,参数有误", null);
		}
		//审核"身份认证"
		verify.setMts(new Date());
		
		//管理端调用时,modifier从session中获取
		String modifier = null;
		//ocr识别自动审核调用时,不能获取request,将报No thread-bound request found错误
		try {
			modifier = (String) session.getAttribute("uid");
		} catch (Exception e) {
			modifier = uid;
		}
		
		verify.setModifier(modifier);
		verify.setState(verifyEntity.getState());
		verify.setCheckResult(verifyEntity.getCheckResult());
		verify.setValidDate(verifyEntity.getValidDate());
		verify.setAutoCheckResult(verifyEntity.getAutoCheckResult());
		//同步数据
		SynDream2020DataModel data = new SynDream2020DataModel();
		data.setCasid(uid);
		
		//若认证成功,写入认证成功时间,更新实名信息,同时需更新realname,verified字段
		if(Constant.TWO == verify.getState()) {
			UserEntity user = userDao.queryUserByUid(uid);
			//检查有效期数据合法性
			if(verify.getValidDate() != null && (verify.getValidDate() < 0 || verify.getValidDate() > Constant.MAX_VALID_DATE)) {
				logger.warn("审核失败,有效期数据不合法:(");
				properties.put("failure_reason", "有效期不合法");
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_RESULT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("审核失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0112-6,请联系管理员", null);
				}
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "审核失败,有效期不合法", null);
			}
			verify.setVerifySuccessts(new Date());
			
			//使用实名信息直接覆盖"实名认证"信息
			RealNameTmpEntity tmp = tmpDao.queryTmpByUid(uid);
			if(tmp == null) {
				logger.warn("审核失败,未查找到相应的实名信息:(");
				properties.put("failure_reason", "实名信息为空");
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_RESULT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("审核失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0112-7,请联系管理员", null);
				}
				return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "审核失败,实名信息不存在", null);
			}
			//身份中间表覆盖实名表  当后台审核时 覆盖  == 但是当身份是个人时（身份已通过的不覆盖）
			if (StringUtils.isEmpty(processType)) {
				RealNameAuthEntity realNameAuth = authDao.queryAuthByUid(verify.getUid());
				if( realNameAuth == null) {
					realNameAuth = new RealNameAuthEntity();
				}
				if (verify.getSort() > Constant.HUNDRED 
						|| realNameAuth.getState() == null
						|| realNameAuth.getState() != Constant.TWO ) {
					
					BeanUtils.copyProperties(tmp, realNameAuth);
					realNameAuth.setState(Constant.TWO);
					realNameAuth.setCheckResult("实名认证成功");
					realNameAuth.setVerifySuccessts(new Date());
					realNameAuth.setModifier(modifier);
					realNameAuth.setMts(new Date());
					//机构负责人实名
					if(verify.getSort() > Constant.HUNDRED) {
						realNameAuth.setIsOrgAuth(Constant.ONE);
					} else {
						realNameAuth.setIsOrgAuth(Constant.ZERO);
					}
					try {
						//神策数据 设置用户属性
						sa.profileSet(uid, true, "name", realNameAuth.getRealName());
					} catch (InvalidArgumentException e) {
						logger.warn("审核失败," + e.getMessage());
						return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0315-2,请联系管理员", null);
					}
					authDao.replaceRealNameAuth(realNameAuth);
				}
			}
			//添加实名用户角色
			userRoleDao.replaceUserRoleById(uid,Constant.REALNAME_ROLE_ID);
			//添加uid-rleId
			userRoleDao.replaceUserRoleById(uid, rleId);
			
			//官方认证通过后,uname变为机构名称
			if(Constant.HUNDRED < verify.getSort()) {
				String oriUname = "";
				if(user != null) {
					oriUname = user.getUname();
					user.setUname(verify.getCompany());
					user.setIsChangedUname(Constant.ONE);
					user.setModifier(modifier);
					user.setMts(new Date());					
					userDao.updateUser(user);
				}
				data.setName(verify.getCompany());
				
				//同步梦想文库数据
				//官方认证填写的company不为空&现uname与原uname不一致时,执行同步操作
				if(!StringUtils.isEmpty(verify.getCompany()) && !verify.getCompany().equals(oriUname)) {
					SynLibraryUserEntity libraryUser = new SynLibraryUserEntity();
					libraryUser.setCasid(uid);
					libraryUser.setUname(oriUname);
					libraryUser.setUsername(verify.getCompany());
					synLibraryService.synLibraryUser(libraryUser);
				}
			}
			
			//"梦想教师认证"认证通过后,添加角色并同步相关字段
			if(verify.getSort() == Constant.TEACHER_SORT && !StringUtils.isEmpty(verify.getSchool()) && !StringUtils.isEmpty(verify.getSchool().getSid())) {
				//更新认证学校信息
				verifyDao.updateSidVerifiesByUidAndDr(uid, verify.getSchool().getSid(), Constant.ONE);
				data.setName(user.getUname());
				if(user.getSex() == null) {
					data.setSex(Constant.ZERO);
				} else if(Constant.MALE.equals(user.getSex())) {
					data.setSex(Constant.ONE);
				} else {					
					data.setSex(Constant.TWO);
				}
				data.setEmail(user.getEmail());
				data.setPhone(user.getPhone());
				data.setSchoolNumber(verify.getSchool().getSid());
				data.setCreateTime(verify.getCts().getTime() / 1000);
				data.setIsTeacher(true);
				//神策数据设置用户属性
				try {
					sa.profileSet(uid, true, "sname", verify.getSchool().getSname());
				} catch (InvalidArgumentException e) {
					logger.warn("审核失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0315-3,请联系管理员", null);
				}
			}
			
			//"身份认证"认证成功,更新用户真实姓名;
			//认证失败,不影响用户真实姓名
			if(user != null) {
				user.setRealName(tmp.getRealName());
				user.setVerified(Integer.toString(Constant.ONE));
				user.setModifier(modifier);
				user.setMts(new Date());
				userDao.updateRealName(user);				
			}
			
			//认证通过需同步realname字段
			data.setRealname(tmp.getRealName());
			data.setVerified(Constant.VERIFIED);
			
			//身份认证审核失败,不进行同步操作
			if(verifyDao.checkVerify(verify) == 0) {
				logger.warn("审核失败,内部出错:(");
				properties.put("failure_reason", "系统错误");
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_RESULT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("审核失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0112-8,请联系管理员", null);
				}
				return new ResultModel<String>(ResultModel.ERR_DATABASE, "审核失败,请联系管理员", null);
			}
			
			//若认证成功，将认证信息写入用户历史认证记录表中
			//当前用户认证的角色是否存在，若存在将已存在的角色置为历史（非当前用户角色）
			verifyHistoryDao.updateVerifyHistory(uid,rleId);
			String guid = IdGenerator.getGuid();
			verify.setSid(verify.getSchool() == null? null:verify.getSchool().getSid());
			verify.setBsId(verify.getScale() == null? null:verify.getScale().getBsId());
			verify.setGid(verify.getGrade() == null? null:verify.getGrade().getGid());
			verify.setCategoryId(verify.getCategory() == null ? null:verify.getCategory().getCategoryId());
			verify.setEtid(verify.getEconomicType() == null? null:verify.getEconomicType().getEtid());
			verify.setCpRleId(verify.getCoachPlanRole() == null ? null:verify.getCoachPlanRole().getCpRleId());
			verifyHistoryDao.insertVerifyHistory(guid,verify);
			
			//若审核的认证中包含学校信息&&不为梦想教师认证,将更新该用户其他认证信息中的学校信息
			if(verify.getSort() != Constant.TEACHER_SORT && verify.getSchool() != null 
					&& !StringUtils.isEmpty(verify.getSchool().getSid()) && StringUtils.hasText(verify.getSchool().getSid())) {
				//更新认证学校信息
				verifyDao.updateSidVerifiesByUidAndDr(uid, verify.getSchool().getSid(), Constant.ONE);
				List<UserVerifyEntity> containSchoolVerifies = verifyDao.queryContainSchoolVerifiesByUidAndDr(uid, Constant.ONE);
				//梦想教师认证需要同步至盒子
				if(!Utils.isEmptyCollection(containSchoolVerifies)) {
					Optional<UserVerifyEntity> result = containSchoolVerifies.stream().filter(v -> v.getSort() == Constant.TEACHER_SORT).findFirst();
					if(result.orElse(null) != null) {
						UserVerifyEntity teacherVerify = result.orElse(null);
						data.setName(user.getUname());
						if(user.getSex() == null) {
							data.setSex(Constant.ZERO);
						} else if(Constant.MALE.equals(user.getSex())) {
							data.setSex(Constant.ONE);
						} else {					
							data.setSex(Constant.TWO);
						}
						data.setEmail(user.getEmail());
						data.setPhone(user.getPhone()); 
						data.setSchoolNumber(verify.getSchool().getSid());
						data.setCreateTime(teacherVerify.getCts().getTime() / 1000);
						data.setIsTeacher(teacherVerify.getState() == Constant.TWO ? true : false);
					}
				}
			}
			synDream2020Service.synDream2020Data(data);
			properties.put("review_status", "通过");
			properties.put("failure_reason", "");
			try {
				sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_RESULT, properties);
				sa.flush();
				UserRoleLinkEntity userRole = userRoleDao.queryRolesByUidAndDr(uid, Constant.ONE);
				sa.profileSet(uid, true, "role_name", userRole != null
						? userRole.getRleName() : "");
				//是否认证
				sa.profileSet(uid, true, "certification", true);
				//认证类型
				UserRoleLinkEntity userRoleVerify = userRoleDao.queryRolesByUidAndDrAndVerify(uid, Constant.ONE, Constant.ONE);
				sa.profileSet(uid, true, "certification_type", userRoleVerify != null
						? userRoleVerify.getRleName() : "");				
			} catch (InvalidArgumentException e) {
				logger.warn("审核失败," + e.getMessage());
				return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0112-9,请联系管理员", null);
			}
			return new ResultModel<String>(ResultModel.SUCCESS, "审核成功", null);
		} else {
			verify.setValidDate(null);
			verify.setVerifySuccessts(null);
			if(verifyDao.checkVerify(verify) == 0) {
				logger.warn("审核失败,内部出错:(");
				properties.put("failure_reason", "系统错误");
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_RESULT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("审核失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0112-10,请联系管理员", null);
				}
				return new ResultModel<String>(ResultModel.ERR_DATABASE, "审核失败,请联系管理员", null);
			}
			
			//去除user-role对应的uid-rleId
			userRoleDao.deleteUserRole(uid, rleId);
			/**
			 * '梦想教师'认证失败,同步isTeacher,isDreamDirector数据
			 * '志愿者'认证暂不同步
			 * 其他认证方式不影响相关字段,不进行同步
			 */
			if(Constant.TEACHER_SORT == verify.getSort()) {
				//去除'梦想中心主任'角色
				userRoleDao.deleteUserRole(uid, Constant.DREAM_DIRECTOR_ROLE_ID);
				data.setSchoolNumber(verify.getSchool().getSid());
				data.setIsTeacher(false);
				data.setIsDreamDirector(false);
				synDream2020Service.synDream2020Data(data);
			}
			//'认证状态'不为空&&不为'审核中'
			if(verify.getState() != null && verify.getState() != Constant.ONE) {
				properties.put("failure_reason", verify.getCheckResult());
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_RESULT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("审核失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0112-8,请联系管理员", null);
				}
			}
			return new ResultModel<String>(ResultModel.SUCCESS, "审核成功", null);
		}
	}
	
	/**
	 * 新增或更新身份认证  前端提交
	 * @param uid
	 * @param rleId
	 * @param verifyEntity
	 * @return
	 */
	public ResultModel<?> saveOrUpdateVerify(String uid,String rleId,UserVerifyEntity verifyEntity) {
		logger.debug("根据uid,rleId更新UserVerify");
		if(StringUtils.isEmpty(uid) || StringUtils.isEmpty(rleId) || verifyEntity == null) {
			if(StringUtils.isEmpty(uid)) {
				logger.warn("操作失败,请求参数有误:(11");
			}
			if(StringUtils.isEmpty(rleId)) {
				logger.warn("操作失败,请求参数有误:(22");
			}
			if(verifyEntity == null) {
				logger.warn("操作失败,请求参数有误:(33");
			}
			return new ResultModel<String>(ResultModel.ERR_PARAM, ResultModel.ERR_PARAM_MSG, null);
		}
		//查询用户角色
		List<String> rleIds = userDao.getUserRoleIdsByUid(uid);
		//角色不为空&&梦想中心学校账号
		if(!Utils.isEmptyCollection(rleIds) && rleIds.contains(Constant.DREAM_SCHOOL_ROLE_ID)) {
			logger.warn("学校账号:" + uid + "进行了认证,已驳回:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "学校账号,无需认证,请使用个人账号", null);
		}
		verifyEntity.setModifier(uid);
		verifyEntity.setMts(new Date());
		verifyEntity.setState(Constant.ONE);
		verifyEntity.setCheckResult("正在审核中,请您耐心等候.");
		verifyEntity.setDr(Constant.ONE);
		
		
		String oriPhone = null;
		String oriEmail = null;
		// 4种去远方ID校验  认证成功的不允许修改
		//再增加4种教练计划ID
		//  认证失败的或者审核中的 不同relId 删除原来的
		switch (rleId) {
		case Constant.GFA_TEACHER_ID:
		case Constant.GFA_STUDENT_ID:
		case Constant.GFA_VOL_A_ID:
		case Constant.GFA_VOL_B_ID:
			
			//查询所有的去远方认证 。逻辑上只有一个
			List<String> roleIds = new ArrayList<String>();
			roleIds.add(Constant.GFA_TEACHER_ID);
			roleIds.add(Constant.GFA_STUDENT_ID);
			roleIds.add(Constant.GFA_VOL_A_ID);
			roleIds.add(Constant.GFA_VOL_A_ID);
			List<UserVerifyEntity> list = verifyDao.queryByRoleIds(uid, roleIds);
			
			if(list == null || list.size() == 0) break;
			if(list.size() > 1) {
				return new ResultModel<String>(ResultModel.ERR_USER_INFO, "去远方身份存在多个，请联系管理员删除", null);
			}
			for(UserVerifyEntity gfaVerifyEntity:list) {
				oriEmail = gfaVerifyEntity.getEmail();
				oriPhone = gfaVerifyEntity.getPhone();
				if(gfaVerifyEntity.getState() == 2 ) {
					if(!rleId.equals(gfaVerifyEntity.getRleId())) {
						return new ResultModel<String>(ResultModel.ERR_USER_INFO, "不允许修改已认证角色", null);
					}
				} else {
					if(!rleId.equals(gfaVerifyEntity.getRleId())) {
						gfaVerifyEntity.setDr(0);
						verifyDao.deleteUserVerify(gfaVerifyEntity);
					}
				}
			}
			break;
		//教练计划认证
		case Constant.COACH_PLAN_A_ID:
		case Constant.COACH_PLAN_B_ID:
		case Constant.COACH_PLAN_C_ID:
		case Constant.COACH_PLAN_D_ID:
			//查询所有的教练计划认证 。逻辑上只有一个
			List<String> coachPlanIds = new ArrayList<String>();
			coachPlanIds.add(Constant.COACH_PLAN_A_ID);
			coachPlanIds.add(Constant.COACH_PLAN_B_ID);
			coachPlanIds.add(Constant.COACH_PLAN_C_ID);
			coachPlanIds.add(Constant.COACH_PLAN_D_ID);
			List<UserVerifyEntity> coachPlanVerfies = verifyDao.queryByRoleIds(uid, coachPlanIds);
			
			if(Utils.isEmptyCollection(coachPlanVerfies)) break;
			if(coachPlanVerfies.size() > 1) {
				return new ResultModel<String>(ResultModel.ERR_USER_INFO, "教练计划身份认证存在多个，请联系管理员删除", null);
			}
			for(UserVerifyEntity coachPlanVerify:coachPlanVerfies) {
				oriEmail = coachPlanVerify.getEmail();
				oriPhone = coachPlanVerify.getPhone();
				if(coachPlanVerify.getState() == 2 ) {
					if(!rleId.equals(coachPlanVerify.getRleId())) {
						return new ResultModel<String>(ResultModel.ERR_USER_INFO, "不允许修改已认证成功角色", null);
					}
				} else {
					if(!rleId.equals(coachPlanVerify.getRleId())) {
						coachPlanVerify.setDr(0);
						verifyDao.deleteUserVerify(coachPlanVerify);
					}
				}
			}
			break;
		default:
			break;
		}
		UserVerifyEntity verify = verifyDao.queryVerifyByUidAndRleId(uid, rleId);
		//是否之前已进行过身份认证
		if(verify == null) {
			verifyEntity.setCreator(uid);
			verifyEntity.setCts(new Date());
			verifyEntity.setModifier(uid);
			verifyEntity.setMts(new Date());
			
			//手机号包含*
			if(!StringUtils.isEmpty(oriPhone) 
					&& !StringUtils.isEmpty(verifyEntity.getPhone()) 
					&& verifyEntity.getPhone().indexOf("*") != -1) {
				if(!Utils.replaceXing(oriPhone, 3, 4).equals(verifyEntity.getPhone())) {
					logger.warn("更新出错,提交含有*的手机号与之前手机号不一致,oriPhone:" + oriPhone + ",phone:" + verifyEntity.getPhone());
					return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,手机号有误", null);
				} else {
					verifyEntity.setPhone(oriPhone);
				}
			}
			//email包含*
			if(!StringUtils.isEmpty(oriEmail)
					&& !StringUtils.isEmpty(verifyEntity.getEmail()) 
					&& verifyEntity.getEmail().indexOf("*") != -1) {
				if(!Utils.hideEmail(oriEmail).equals(verifyEntity.getEmail())) {
					logger.warn("更新出错,提交含有*的邮箱号与之前手机号不一致,oriEmail:" + oriEmail + ",email:" + verifyEntity.getEmail());
					return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,邮箱有误", null);
				} else {
					verifyEntity.setEmail(oriEmail);
				}
			}
			verifyDao.addUserVerify(verifyEntity);
		} else {
			//已进行过身份认证
			oriPhone = verify.getPhone();
			oriEmail = verify.getEmail();
			//手机号包含*
			if(!StringUtils.isEmpty(oriPhone) 
					&& !StringUtils.isEmpty(verifyEntity.getPhone()) 
					&& verifyEntity.getPhone().indexOf("*") != -1) {
				if(!Utils.replaceXing(oriPhone, 3, 4).equals(verifyEntity.getPhone())) {
					logger.warn("更新出错,提交含有*的手机号与之前手机号不一致,oriPhone:" + oriPhone + ",phone:" + verify.getPhone());
					return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,手机号有误", null);
				} else {
					verifyEntity.setPhone(oriPhone);
				}
			}
			//email包含*
			if(!StringUtils.isEmpty(oriEmail)
					&& !StringUtils.isEmpty(verifyEntity.getEmail()) 
					&& verifyEntity.getEmail().indexOf("*") != -1) {
				if(!Utils.hideEmail(oriEmail).equals(verifyEntity.getEmail())) {
					logger.warn("更新出错,提交含有*的邮箱号与之前手机号不一致,oriEmail:" + oriEmail + ",email:" + verify.getEmail());
					return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,邮箱有误", null);
				} else {
					verifyEntity.setEmail(oriEmail);
				}
			}
			Utils.copyPropertiesIgnoreNull(verifyEntity, verify);
			verify.setCity(verifyEntity.getCity());
			verify.setArea(verifyEntity.getArea());
			//设置已认证成功后重新修改认证的verifySuccessts和validDate字段
			verify.setVerifySuccessts(null);
			verify.setValidDate(null);
			verifyDao.updateUserVerify(verify);
		}
		
		UserVerifyEntity entity =  verify == null? verifyEntity:verify;
		//异步处理身份认证 
		switch (entity.getRleId()) {
		case Constant.TEACHER_ROLE_ID://梦想教师
		case Constant.GFA_TEACHER_ID:
		case Constant.GFA_STUDENT_ID:
		case Constant.GFA_VOL_A_ID:
		case Constant.GFA_VOL_B_ID:
		case Constant.SPORTS_CLASS_ID:
		case Constant.HTC_H_ID:
		case Constant.EXCELLENCE_ADREAM_HEAD_MASTER_ENROLL_ROLE_ID:
			ocrService.autoUserVerify(entity);
			break;
		default:
			break;
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	
	
	/**
	 * 根据删除标志查询
	 * @param dr 删除标志
	 * @return
	 */
	public List<UserVerifyEntity> queryVerifiesByDr(Integer dr) {
		return verifyDao.queryVerifiesByDr(dr);
	}
	
	/**
	 * 根据user id,删除标志查询
	 * @param uid user id
	 * @param dr 删除标志
	 * @return
	 */
	public List<UserVerifyEntity> queryVerifiesByUidAndDr(String uid,Integer dr) {
		return verifyDao.queryVerifiesByUidAndDr(uid, dr);
	}
	
	/**
	 * 根据role id,删除标志查询
	 * @param rleId role id
	 * @param dr 删除标志
	 * @return
	 */
	public List<UserVerifyEntity> queryVerifiesByRleIdAndDr(String rleId,Integer dr) {
		return verifyDao.queryVerifiesByRleIdAndDr(rleId, dr);
	}
	
	/**
	 * 根据user id,role id
	 * @param uid user id
	 * @param rleId role id
	 * @return
	 */
	public UserVerifyEntity queryVerifiesByUidAndRleId(String uid,String rleId) {
		return verifyDao.queryVerifyByUidAndRleId(uid, rleId);
	}
	
	/**
	 * 根据user id,role id,删除标志查询
	 * @param uid user id
	 * @param rleId role id
	 * @param dr 删除标志
	 * @return
	 */
	public UserVerifyEntity queryVerifiesByUidAndRleIdAndDr(String uid,String rleId,Integer dr) {
		if("gofaraway".equals(rleId.trim().toLowerCase())) {
			return verifyDao.queryGoFarAwayVerify(uid,dr);
		}
		if("coachplan".equals(rleId.trim().toLowerCase())) {
			return verifyDao.querycoachPlanVerify(uid,dr);
		}
		if("htc".equals(rleId.trim().toLowerCase())) {
			return verifyDao.queryHtcVerify(uid,dr);
		}
		if("adreamcenter".equals(rleId.trim().toLowerCase())) {
			UserVerifyEntity entity =  verifyDao.queryAdreamCenterVerify(uid,dr);
			if(entity == null) {
				return entity;
			}
			RoleEntity roleEntity = roleDao.queryRoleByRleId(entity.getRleId());
			CoachPlanRoleEntity coachPlanRoleEntity = new CoachPlanRoleEntity();
			coachPlanRoleEntity.setCpRleName(roleEntity.getRleName());
			entity.setCoachPlanRole(coachPlanRoleEntity);
			return entity;
		}
		return verifyDao.queryVerifyByUidAndRleIdAndDr(uid, rleId, dr);
	}
	
	/**
	 * 根据一些条件模糊查询Userverify
	 * @param realName 真实姓名
	 * @param rleId role id
	 * @param state 认证状态
	 * @param dr  删除标志
	 * @param pageNo   当前页数
	 * @param pageSize 每页展示数目
	 * @return
	 */
	public PageInfo<UserVerifyEntity> queryVerifiesBySomeInfo(String uid, String realName,String rleId,Integer state,
			Integer dr,Integer pageNo,Integer pageSize) {
		pageNo = (pageNo == null) ? Constant.ONE : pageNo;
		pageSize = (pageSize == null) ? Constant.TEN : pageSize;
		PageHelper.startPage(pageNo,pageSize);
		List<UserVerifyEntity> verifies = verifyDao.queryVerifiesBySomeInfo(uid, realName, rleId, state, dr);
		PageInfo<UserVerifyEntity> page = new PageInfo<>(verifies,Constant.TEN);
		return page;
	}
	
	/**
	 * 查询梦想教师认证信息
	 * @param uid  user id
	 * @param rleId role id
	 * @param dr  删除标志
	 * @return
	 */
	public UserVerifyEntity queryTeacherInfo(String uid,String rleId,Integer dr) {
		return verifyDao.queryTeacherInfo(uid, rleId, dr);
	}
	
	/**
	 * 查询用户最近的"身份认证"
	 * @param uid user id
	 * @param dr  删除标志
	 * @return
	 */
	public ResultModel<?> queryRecentVerify(String uid, Integer dr) {
		logger.debug("查询用户最近的身份认证信息");
		if (StringUtils.isEmpty(uid) || dr == null) {
			logger.warn("查询出错,请求参数为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, ResultModel.ERR_PARAM_MSG, null);
		}
		//按mts降序,cts降序的"身份认证"
		List<UserVerifyEntity> userVerifies = verifyDao.queryVerifiesByUidAndDr(uid, dr);
		if(userVerifies == null || userVerifies.size() == Constant.ZERO) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "查询出错,未查询到相应数据", null);
		}
		//第一个则为最近的"身份认证"
		UserVerifyEntity userVerify = userVerifies.get(Constant.ZERO);
		return new ResultModel<UserVerifyEntity>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, userVerify);
	}
	
	/**
	 * 查询用户教练计划认证成功的角色
	 * @param uid	user id
	 * @return
	 */
	public ResultModel<?> queryUserCoachPlanRole(String uid) {
		logger.info("查询用户教练计划认证成功的角色");
		CoachPlanRoleEntity cpRole = verifyDao.queryCoachPlanRole(uid, Constant.COACH_PLAN_ROLE_ID, Constant.TWO, Constant.ONE);
		if(cpRole == null) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "查询出错,无相关数据", null);
		}
		return new ResultModel<CoachPlanRoleEntity>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, cpRole);
	}
	
	/**
	 * 开启定时任务进行审核身份认证是否过期
	 * 每天的00:00执行
	 */
	@Scheduled(cron = "0 0 0 1/1 * ?") // 间隔1天执行
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = ADreamServiceException.class, isolation = Isolation.DEFAULT)
	public void checkIsExpireVerifies() {
		//查询认证成功,但有效期已到,需将认证状态置为认证过期
		List<UserVerifyEntity> verifies = verifyDao.queryExpireVerifiesByStateAndDr(Constant.TWO, Constant.ONE);
		if(!Utils.isEmptyCollection(verifies)) {
			verifies.forEach(v -> {
				//设置任务状态为'已过期'
				v.setState(Constant.FOUR);
				v.setCheckResult("您的{" + Utils.getAuthName(v.getSort()) + "}认证已过期");
				v.setValidDate(null);
				v.setVerifySuccessts(null);
				v.setModifier("system");
				v.setMts(new Date());
				int result = verifyDao.checkVerify(v);
				if(result == Constant.ZERO) {
					logger.warn("定时任务审核已过期的认证失败,系统错误:(,具体时间:" + new Date());
					return;
				}
				//去除user-role对应的uid-rleId
				userRoleDao.deleteUserRole(v.getUid(), v.getRleId());
				
				//同步数据
				SynDream2020DataModel data = new SynDream2020DataModel();
				data.setCasid(v.getUid());
				
				//获取身份认证类型
				if(v.getSort() == Constant.TEACHER_SORT) {
					//'梦想教师认证'认证过期,同步schoolNumber,isTeacher等字段
					data.setSchoolNumber(v.getSid());
					data.setIsTeacher(false);
					data.setIsDreamDirector(false);
					synDream2020Service.synDream2020Data(data);
				}
			});
		}
	}
 
	public ResultModel<?> getRoleInfoByUnionid(String unionid, HttpServletRequest req) throws ADreamServiceException{
		UserEntity userEntity = userDao.searchByUnionid(unionid);
		if(userEntity == null) {
			return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
		}
		List<String> roleIds = new ArrayList<String>();
		roleIds.add(Constant.BUSINESS_ROLE_ID);
		roleIds.add(Constant.ORG_ROLE_ID);
		roleIds.add(Constant.PUBLIC_WELFARE_TEAM_ROLE_ID);
		int count = verifyDao.queryCountNotInRoleIds(userEntity.getUid(),roleIds);
		if(count > 0) {
			return new ResultModel<String>(ResultModel.ERR_USER_INFO, "其他身份正在认证中或已认证", null);
		}
		List<UserVerifyEntity> userVerifyList = verifyDao.queryByRoleIds(userEntity.getUid(),roleIds);
		return new ResultModel<List<UserVerifyEntity>>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, userVerifyList);
	}

	public PageInfo<UserVerifyEntity> queryVerifiesByDataTable(DataTableRequest dtr) {
		PageHelper.startPage(dtr.getStart()/dtr.getLength()+1, dtr.getLength());
		List<UserVerifyEntity> oel= verifyDao.queryVerifiesByDataTable(dtr);
		PageInfo<UserVerifyEntity> oelp = new PageInfo<>(oel);
		return oelp;
	}

	public HSSFWorkbook createWorkBookByState(String rleId, String state, String where,String title) {
		List<Map<String, Object>> list = verifyDao.queryVerifiesByRleIdAndStateAndWhere(rleId, state,where);
		//根据身份ID 判断 共多少列   大于11  基础项目 10
		int preColNum = 13;
		switch (rleId) {
		case Constant.COACH_PLAN_A_ID:
		case Constant.COACH_PLAN_B_ID:
		case Constant.COACH_PLAN_C_ID:
		case Constant.COACH_PLAN_D_ID:
			preColNum = 18;
			break;
		case Constant.TEACHER_ROLE_ID:
			preColNum = 19;
			break;
		default:
			preColNum = 13;
		}
		
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet(title);
		
		// 标题样式
		HSSFCellStyle titleStyle = workbook.createCellStyle(); 
		titleStyle.setAlignment(HorizontalAlignment.CENTER);
		titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		// 边框
		titleStyle.setBorderBottom(BorderStyle.THIN);
		titleStyle.setBorderLeft(BorderStyle.THIN);
		titleStyle.setBorderRight(BorderStyle.THIN);
		titleStyle.setBorderTop(BorderStyle.THIN);
		// 标题字体
	    HSSFFont font = workbook.createFont();
	    font.setFontName(HSSFFont.FONT_ARIAL);
	    font.setColor(IndexedColors.BLACK.getIndex());
	    font.setBold(true);
	    font.setFontHeightInPoints((short) 16);
	    titleStyle.setFont(font);
		
		// 标题
		HSSFRow row = sheet.createRow(0);
		for (int i = 0; i < preColNum; i++) {
		    HSSFCell cell = row.createCell(i);
		    cell.setCellStyle(titleStyle);
		}
		row.getCell(0).setCellValue("（"+ title + "）身份认证信息");
		
		
		row = sheet.createRow(1);
		for (int i = 0; i < preColNum; i++) {
		    HSSFCell cell = row.createCell(i);
		    cell.setCellStyle(titleStyle);
		}
		row.getCell(0).setCellValue("基本信息");
		row.getCell(11).setCellValue("表单信息");
		
		
		sheet.addMergedRegion(new CellRangeAddress(0,0,0,preColNum-1));
		sheet.addMergedRegion(new CellRangeAddress(1,1,0,10));
		sheet.addMergedRegion(new CellRangeAddress(1,1,11,preColNum-1));
		
		switch (rleId) {
		case Constant.COACH_PLAN_A_ID:
		case Constant.COACH_PLAN_B_ID:
		case Constant.COACH_PLAN_C_ID:
		case Constant.COACH_PLAN_D_ID:
			//创建教练计划 表单  第三行开始
			createSheetOfCoachPlan(sheet,list,title);
			break;
		case Constant.TEACHER_ROLE_ID:
			createSheetOfTeacher(sheet,list,title);
			break;
		default:
			return workbook;
		}
		return workbook;
	}

	private void createSheetOfTeacher(HSSFSheet sheet, List<Map<String, Object>> list, String title) {
		if(list ==  null || list.size() == 0) {
			return;
		}
		HSSFRow titleRow = sheet.createRow(2);
		titleRow.createCell(0).setCellValue("uid");
		titleRow.createCell(1).setCellValue("姓名");
		titleRow.createCell(2).setCellValue("性别");
		titleRow.createCell(3).setCellValue("身份证号");
		titleRow.createCell(4).setCellValue("手机");
		titleRow.createCell(5).setCellValue("邮箱");
		titleRow.createCell(6).setCellValue("学校");
		titleRow.createCell(7).setCellValue("账户名");
		titleRow.createCell(8).setCellValue("银行账号");
		titleRow.createCell(9).setCellValue("开户行");
		titleRow.createCell(10).setCellValue("开户支行");
		
		titleRow.createCell(11).setCellValue("工作单位");
		titleRow.createCell(12).setCellValue("rleId");
		titleRow.createCell(13).setCellValue("认证方式");
		titleRow.createCell(14).setCellValue("所教科目");
		titleRow.createCell(15).setCellValue("职称");
		titleRow.createCell(16).setCellValue("职务");
		titleRow.createCell(17).setCellValue("教龄");
		titleRow.createCell(18).setCellValue("简介");
		
		
		for(int i = 0;i<list.size();i++) {
			Map<String, Object> map = list.get(i) ;
			HSSFRow row = sheet.createRow(i+3);
			row.createCell(0).setCellValue(map.get("uid")+"");
			row.createCell(1).setCellValue(map.get("realName")+"");
			row.createCell(2).setCellValue(map.get("userSex")+"");
			row.createCell(3).setCellValue(map.get("creNum")+"");
			row.createCell(4).setCellValue(map.get("userPhone")+"");
			row.createCell(5).setCellValue(map.get("userEmail")+"");
			row.createCell(6).setCellValue(map.get("sname")+"");
			row.createCell(7).setCellValue(map.get("accountName")+"");
			row.createCell(8).setCellValue(map.get("bankAccount")+"");
			row.createCell(9).setCellValue(map.get("depositBank")+"");
			row.createCell(10).setCellValue(map.get("aopenBranch")+"");
			
			row.createCell(11).setCellValue(map.get("sname")+"");
			row.createCell(12).setCellValue(map.get("rleId")+"");
			row.createCell(13).setCellValue(title);
			row.createCell(14).setCellValue(map.get("subject")+"");
			row.createCell(15).setCellValue(map.get("gid")+"");
			row.createCell(16).setCellValue(map.get("job")+"");
			row.createCell(17).setCellValue(map.get("eduage")+"");
			row.createCell(18).setCellValue(map.get("intro")+"");
		}
		
	}

	private void createSheetOfCoachPlan(HSSFSheet sheet, List<Map<String, Object>> list,String title) {
		if(list ==  null || list.size() == 0) {
			return;
		}
		HSSFRow titleRow = sheet.createRow(2);
		titleRow.createCell(0).setCellValue("uid");
		titleRow.createCell(1).setCellValue("姓名");
		titleRow.createCell(2).setCellValue("性别");
		titleRow.createCell(3).setCellValue("身份证号");
		titleRow.createCell(4).setCellValue("手机");
		titleRow.createCell(5).setCellValue("邮箱");
		titleRow.createCell(6).setCellValue("学校");
		titleRow.createCell(7).setCellValue("账户名");
		titleRow.createCell(8).setCellValue("银行账号");
		titleRow.createCell(9).setCellValue("开户行");
		titleRow.createCell(10).setCellValue("开户支行");
		
		titleRow.createCell(11).setCellValue("年份");
		titleRow.createCell(12).setCellValue("rleId");
		titleRow.createCell(13).setCellValue("认证方式");
		titleRow.createCell(14).setCellValue("手机号");
		titleRow.createCell(15).setCellValue("邮箱");
		titleRow.createCell(16).setCellValue("机构/单位");
		titleRow.createCell(17).setCellValue("认证状态");
		
		
		for(int i = 0;i<list.size();i++) {
			Map<String, Object> map = list.get(i) ;
			HSSFRow row = sheet.createRow(i+3);
			row.createCell(0).setCellValue(map.get("uid")+"");
			row.createCell(1).setCellValue(map.get("realName")+"");
			row.createCell(2).setCellValue(map.get("userSex")+"");
			row.createCell(3).setCellValue(map.get("creNum")+"");
			row.createCell(4).setCellValue(map.get("userPhone")+"");
			row.createCell(5).setCellValue(map.get("userEmail")+"");
			row.createCell(6).setCellValue(map.get("sname")+"");
			row.createCell(7).setCellValue(map.get("accountName")+"");
			row.createCell(8).setCellValue(map.get("bankAccount")+"");
			row.createCell(9).setCellValue(map.get("depositBank")+"");
			row.createCell(10).setCellValue(map.get("aopenBranch")+"");
			
			row.createCell(11).setCellValue(map.get("cpYear")+"");
			row.createCell(12).setCellValue(map.get("rleId")+"");
			row.createCell(13).setCellValue(title);
			row.createCell(14).setCellValue(map.get("phone")+"");
			row.createCell(15).setCellValue(map.get("email")+"");
			row.createCell(16).setCellValue(map.get("company")+"");
			
			String state = String.valueOf(map.get("state"));
			String stateString = "";
			switch (state) {
			case "1": stateString="认证中"; break;
			case "2": stateString="认证成功"; break;
			case "3": stateString="认证失败"; break;
			case "4": stateString="认证过期"; break;
			default:
				stateString = state;
			}
			row.createCell(17).setCellValue(stateString);
		}
	}
	
	/**
	 * 查询用户最近含有学校信息的"身份认证"
	 * @param uid user id
	 * @param dr  删除标志
	 * @return
	 */
	public ResultModel<?> queryRecentSchoolVerify(String uid, Integer dr) {
	   //按mts降序,cts降序含有学校信息的"身份认证"
	   List<UserVerifyEntity> userVerifies = verifyDao.queryContainSchoolVerifiesByUidAndDr(uid, dr);
	   if(userVerifies == null || userVerifies.size() == Constant.ZERO) {
	      return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "查询出错,未查询到相应数据", null);
	   }
	   //第一个则为最近的"身份认证"
	   UserVerifyEntity userVerify = userVerifies.get(0);
	   return new ResultModel<UserVerifyEntity>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, userVerify);
	}

	public Map<String, String> queryVerifyInfoByUidAndRleId(String uid, String rleId) {
		return verifyDao.queryVerifyInfoByUidAndRleId(uid,rleId);
	}

	public boolean valiSportClassAuth(String uid) {
		UserVerifyEntity verifyEntity = verifyDao.queryVerifyByUidAndRleId(uid, Constant.SPORTS_CLASS_ID);
		if(verifyEntity == null || verifyEntity.getState() != Constant.TWO) {
			return false;
		}
		if(StringUtils.isEmpty(verifyEntity.getSubject()) || StringUtils.isEmpty(verifyEntity.getJob())) {
			return false;
		}
		return true;
	}
}